Repository: Nilhcem/hosts-editor-android Branch: master Commit: 837e40f9958c Files: 59 Total size: 125.4 KB Directory structure: gitextract_bdv5001x/ ├── .gitignore ├── LICENSE.txt ├── README.md ├── app/ │ ├── build.gradle │ ├── libs/ │ │ └── RootTools-4.2.jar │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── com/ │ │ └── nilhcem/ │ │ └── hostseditor/ │ │ ├── HostsEditorApplication.java │ │ ├── core/ │ │ │ ├── Host.java │ │ │ ├── HostsManager.java │ │ │ ├── dagger/ │ │ │ │ ├── HostsEditorComponent.java │ │ │ │ └── HostsEditorModule.java │ │ │ ├── log/ │ │ │ │ └── ReleaseTree.java │ │ │ └── util/ │ │ │ ├── Compatibility.java │ │ │ ├── InetAddresses.java │ │ │ └── ThreadPreconditions.java │ │ ├── event/ │ │ │ ├── CreatedHostEvent.java │ │ │ ├── LoadingEvent.java │ │ │ ├── RefreshHostsEvent.java │ │ │ ├── StartAddEditActivityEvent.java │ │ │ └── TaskCompletedEvent.java │ │ ├── task/ │ │ │ ├── AddEditHostAsync.java │ │ │ ├── GenericTaskAsync.java │ │ │ ├── ListHostsAsync.java │ │ │ ├── RemoveHostsAsync.java │ │ │ └── ToggleHostsAsync.java │ │ └── ui/ │ │ ├── BaseActivity.java │ │ ├── BaseFragment.java │ │ ├── about/ │ │ │ └── AboutDialogFragment.java │ │ ├── addedit/ │ │ │ ├── AddEditHostActivity.java │ │ │ └── AddEditHostFragment.java │ │ ├── list/ │ │ │ ├── ListHostsActivity.java │ │ │ ├── ListHostsAdapter.java │ │ │ ├── ListHostsFragment.java │ │ │ └── ListHostsSearchFilter.java │ │ └── widget/ │ │ ├── CheckableHostItem.java │ │ ├── InertCheckBox.java │ │ ├── TypefacedButton.java │ │ └── TypefacedTextView.java │ └── res/ │ ├── layout/ │ │ ├── about_dialog.xml │ │ ├── add_edit_host_layout.xml │ │ ├── checkable_host_item.xml │ │ ├── list_hosts_empty.xml │ │ ├── list_hosts_fragment.xml │ │ └── list_hosts_layout.xml │ ├── menu/ │ │ ├── add_edit_menu.xml │ │ ├── list_contextual_actions.xml │ │ └── list_menu.xml │ ├── values/ │ │ ├── attrs.xml │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── values-sw720dp-land/ │ └── dimens.xml ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Temporary files *~ \#* tmp/ # Build directory build/ # Eclipse files .metadata .pmd .apt_generated/ # IntelliJ files .idea *.iml # Android built application files *.apk *.ap_ # Files for the dex VM *.dex # Java class files *.class # Generated files bin/ gen/ # Local configuration file (sdk path, etc) local.properties # OSX files .DS_Store # Windows files Thumbs.db # Gradle .gradle ================================================ FILE: LICENSE.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. ================================================ FILE: README.md ================================================ # Hosts Editor for Android This repository contains the source code for the Hosts-editor Android app. It is available from [Google Play][] and [F-Droid][]. ![Hosts Editor for Android screenshots][] This application, **for root devices only**, lets you modify easily your Android `/etc/hosts` file. You might need to reboot to clear your DNS cache after any change. ## Features * Android 2.2 and above * Insert, Remove, Toggle (comment/uncomment) and Modify host entries * Holo theme * Fast search engine * 100% free/libre, gratis, no ads ## Building the app The Android SDK for API level 19 is required to build the app. Then launch: ./gradlew clean build ## Acknowledgements This project uses many great open-source libraries, such as: * [ActionBarSherlock][] * [Butterknife][] * [Dagger][] * [Commons IO][] * [Otto][] * [RootTools][] ## License

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   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.
[Google Play]: https://play.google.com/store/apps/details?id=com.nilhcem.hostseditor [F-Droid]: https://f-droid.org/repository/browse/?fdid=com.nilhcem.hostseditor [Hosts Editor for Android screenshots]: https://raw.githubusercontent.com/Nilhcem/hosts-editor-android/master/screenshot.png [ActionBarSherlock]: http://actionbarsherlock.com/ [Butterknife]: http://jakewharton.github.com/butterknife/ [Dagger]: http://square.github.com/dagger/ [Commons IO]: http://commons.apache.org/proper/commons-io/ [Otto]: http://square.github.com/otto/ [RootTools]: https://code.google.com/p/roottools/ ================================================ FILE: app/build.gradle ================================================ apply plugin: 'com.android.application' apply plugin: 'com.neenbedankt.android-apt' android { compileSdkVersion 22 buildToolsVersion '22.0.1' defaultConfig { applicationId 'com.nilhcem.hostseditor' minSdkVersion 8 targetSdkVersion 22 versionCode 5 versionName '1.4' resConfig 'en' } compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } buildTypes { release { minifyEnabled false } } packagingOptions { exclude 'META-INF/LICENSE.txt' } lintOptions { abortOnError false } } dependencies { // Commons IO compile 'commons-io:commons-io:2.4' // Dagger compile 'com.google.dagger:dagger:2.0.1' apt 'com.google.dagger:dagger-compiler:2.0.1' compile 'javax.annotation:javax.annotation-api:1.2' // ActionBarSherlock + Support library compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar' compile 'com.android.support:support-v4:22.2.0' // Butterknife compile 'com.jakewharton:butterknife:7.0.1' // Logging compile 'com.jakewharton.timber:timber:3.1.0' // Otto compile 'com.squareup:otto:1.3.8' // Other jars (RootTools) compile fileTree(dir: 'libs', include: '*.jar') } ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/HostsEditorApplication.java ================================================ package com.nilhcem.hostseditor; import android.app.Application; import android.content.Context; import com.nilhcem.hostseditor.core.dagger.DaggerHostsEditorComponent; import com.nilhcem.hostseditor.core.dagger.HostsEditorComponent; import com.nilhcem.hostseditor.core.dagger.HostsEditorModule; import com.nilhcem.hostseditor.core.log.ReleaseTree; import timber.log.Timber; public class HostsEditorApplication extends Application { private HostsEditorComponent mComponent; public static HostsEditorApplication get(Context context) { return (HostsEditorApplication) context.getApplicationContext(); } @Override public void onCreate() { super.onCreate(); initLogger(); initGraph(); } public HostsEditorComponent component() { return mComponent; } private void initLogger() { if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } else { Timber.plant(new ReleaseTree()); } } private void initGraph() { mComponent = DaggerHostsEditorComponent.builder() .hostsEditorModule(new HostsEditorModule()) .build(); } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/core/Host.java ================================================ package com.nilhcem.hostseditor.core; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import com.nilhcem.hostseditor.core.util.InetAddresses; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Host implements Parcelable { public static final String STR_COMMENT = "#"; private static final String STR_SEPARATOR = " "; private static final String HOST_PATTERN_STR = "^\\s*(" + STR_COMMENT + "?)\\s*(\\S*)\\s*([^" + STR_COMMENT + "]*)" + STR_COMMENT + "?(.*)$"; private static final Pattern HOST_PATTERN = Pattern.compile(HOST_PATTERN_STR); private String mIp; private String mHostName; private String mComment; // When host entry has a comment at the end, eg: "::1 localhost #myhome" private boolean mIsCommented; // When host entry starts with #, eg: "#::1 localhost" private boolean mIsValid; // When host entry has a valid IP + hostname public Host(String ip, String hostName, String comment, boolean isCommented, boolean isValid) { mIp = ip; mHostName = hostName; mComment = comment; mIsCommented = isCommented; mIsValid = isValid; } public void merge(Host src) { mIp = src.getIp(); mHostName = src.getHostName(); mComment = src.getComment(); mIsCommented = src.isCommented(); mIsValid = src.isValid(); } public String getIp() { return mIp; } public String getHostName() { return mHostName; } public String getComment() { return mComment; } public boolean isValid() { return mIsValid; } public boolean isCommented() { return mIsCommented; } public void toggleComment() { mIsCommented = !mIsCommented; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (mIsCommented) { sb.append(STR_COMMENT); } if (mIp != null) { sb.append(mIp).append(STR_SEPARATOR); } if (mHostName != null) { sb.append(mHostName); } if (!TextUtils.isEmpty(mComment)) { sb.append(STR_SEPARATOR).append(STR_COMMENT).append(mComment); } return sb.toString(); } public static Host fromString(String line) { Matcher matcher = HOST_PATTERN.matcher(line); String ip = null; String hostname = null; String comment = null; boolean isCommented = false; boolean isValid = false; if (matcher.find()) { isCommented = !TextUtils.isEmpty(matcher.group(1)); ip = matcher.group(2); hostname = matcher.group(3).trim(); comment = matcher.group(4).trim(); if (TextUtils.isEmpty(comment)) { comment = null; } isValid = !TextUtils.isEmpty(ip) && !TextUtils.isEmpty(hostname) && InetAddresses.isInetAddress(ip); } return new Host(ip, hostname, comment, isCommented, isValid); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { @Override public Host createFromParcel(Parcel source) { return new Host(source); } @Override public Host[] newArray(int size) { return new Host[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mIp); dest.writeString(mHostName); dest.writeString(mComment); dest.writeByte((byte) (mIsCommented ? 1 : 0)); dest.writeByte((byte) (mIsValid ? 1 : 0)); } private Host(Parcel in) { mIp = in.readString(); mHostName = in.readString(); mComment = in.readString(); mIsCommented = in.readByte() == 1; mIsValid = in.readByte() == 1; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((mComment == null) ? 0 : mComment.hashCode()); result = prime * result + ((mHostName == null) ? 0 : mHostName.hashCode()); result = prime * result + ((mIp == null) ? 0 : mIp.hashCode()); result = prime * result + (mIsCommented ? 1231 : 1237); result = prime * result + (mIsValid ? 1231 : 1237); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Host other = (Host) obj; if (mComment == null) { if (other.mComment != null) { return false; } } else if (!mComment.equals(other.mComment)) { return false; } if (mHostName == null) { if (other.mHostName != null) { return false; } } else if (!mHostName.equals(other.mHostName)) { return false; } if (mIp == null) { if (other.mIp != null) { return false; } } else if (!mIp.equals(other.mIp)) { return false; } if (mIsCommented != other.mIsCommented) { return false; } if (mIsValid != other.mIsValid) { return false; } return true; } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/core/HostsManager.java ================================================ package com.nilhcem.hostseditor.core; import android.content.Context; import com.stericson.RootShell.RootShell; import com.stericson.RootShell.exceptions.RootDeniedException; import com.stericson.RootShell.execution.Command; import com.stericson.RootTools.RootTools; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.concurrent.TimeoutException; import javax.inject.Inject; import javax.inject.Singleton; import timber.log.Timber; @Singleton public class HostsManager { private static final String UTF_8 = "UTF-8"; private static final String HOSTS_FILE_NAME = "hosts"; private static final String HOSTS_FILE_PATH = "/system/etc/" + HOSTS_FILE_NAME; private static final String LINE_SEPARATOR = System.getProperty("line.separator", "\n"); private static final String MOUNT_TYPE_RO = "ro"; private static final String MOUNT_TYPE_RW = "rw"; private static final String COMMAND_RM = "rm -f"; private static final String COMMAND_CHOWN = "chown 0:0"; private static final String COMMAND_CHMOD_644 = "chmod 644"; // Do not access this field directly even in the same class, use getAllHosts() instead. private List mHosts; @Inject public HostsManager() { } /** * Gets all host entries from hosts file. *

Must be in an async call.

* * @param forceRefresh if we want to force using the hosts file (not the cache) * @return a list of host entries */ public synchronized List getHosts(boolean forceRefresh) { if (mHosts == null || forceRefresh) { mHosts = Collections.synchronizedList(new ArrayList()); LineIterator it = null; try { it = FileUtils.lineIterator(new File(HOSTS_FILE_PATH), UTF_8); while (it.hasNext()) { Host host = Host.fromString(it.nextLine()); if (host != null) { mHosts.add(host); } } } catch (IOException e) { Timber.e(e, "I/O error while opening hosts file"); } finally { if (it != null) { LineIterator.closeQuietly(it); } } } return mHosts; } /** * Saves new hosts file and creates a backup of previous file. *

Must be in an async call.

* * @param appContext application context * @return {@code true} if everything was working as expected, or {@code false} otherwise */ public synchronized boolean saveHosts(Context appContext) { if (!RootTools.isAccessGiven()) { Timber.w("Can't get root access"); return false; } // Step 1: Create temporary hosts file in /data/data/project_package/files/hosts if (!createTempHostsFile(appContext)) { Timber.w("Can't create temporary hosts file"); return false; } String tmpFile = String.format(Locale.US, "%s/%s", appContext.getFilesDir().getAbsolutePath(), HOSTS_FILE_NAME); String backupFile = String.format(Locale.US, "%s.bak", tmpFile); // Step 2: Get canonical path for /etc/hosts (it could be a symbolic link) String hostsFilePath = HOSTS_FILE_PATH; File hostsFile = new File(HOSTS_FILE_PATH); if (hostsFile.exists()) { try { if (FileUtils.isSymlink(hostsFile)) { hostsFilePath = hostsFile.getCanonicalPath(); } } catch (IOException e1) { Timber.e(e1, "Can't find hosts file"); } } else { Timber.w("Hosts file was not found in filesystem"); } try { // Step 3: Create backup of current hosts file (if any) RootTools.remount(hostsFilePath, MOUNT_TYPE_RW); runRootCommand(COMMAND_RM, backupFile); RootTools.copyFile(hostsFilePath, backupFile, false, true); // Step 4: Replace hosts file with generated file runRootCommand(COMMAND_RM, hostsFilePath); RootTools.copyFile(tmpFile, hostsFilePath, false, true); // Step 5: Give proper rights runRootCommand(COMMAND_CHOWN, hostsFilePath); runRootCommand(COMMAND_CHMOD_644, hostsFilePath); // Step 6: Delete local file appContext.deleteFile(HOSTS_FILE_NAME); } catch (Exception e) { Timber.e(e, "Failed running root command"); return false; } finally { RootTools.remount(hostsFilePath, MOUNT_TYPE_RO); } return true; } /** * Returns a list of hosts matching the constraint parameter. */ public List filterHosts(CharSequence constraint) { List all = getHosts(false); List hosts = new ArrayList<>(); for (Host host : all) { if (host.isValid()) { if (host.getIp().contains(constraint) || host.getHostName().contains(constraint) || (host.getComment() != null && host.getComment().contains(constraint))) { hosts.add(host); } } } return hosts; } /** * Creates a temporary hosts file in {@code /data/data/project_package/files/hosts}. *

Must be in an async call.

* * @param appContext application context * @return {@code true} if the temp file was created, or {@code false} otherwise */ private boolean createTempHostsFile(Context appContext) { OutputStreamWriter writer = null; try { FileOutputStream out = appContext.openFileOutput(HOSTS_FILE_NAME, Context.MODE_PRIVATE); writer = new OutputStreamWriter(out); for (Host host : getHosts(false)) { writer.append(host.toString()).append(LINE_SEPARATOR); } writer.flush(); } catch (IOException e) { Timber.e(e, "Error creating temporary hosts file"); return false; } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { Timber.e(e, "Error while closing writer"); } } } return true; } /** * Executes a single argument root command. *

Must be in an async call.

* * @param command a command, ie {@code "rm -f"}, {@code "chmod 644"}... * @param uniqueArg the unique argument for the command, usually the file name */ private void runRootCommand(String command, String uniqueArg) throws IOException, TimeoutException, RootDeniedException { Command cmd = new Command(0, false, String.format(Locale.US, "%s %s", command, uniqueArg)); RootShell.getShell(true).add(cmd); } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/core/dagger/HostsEditorComponent.java ================================================ package com.nilhcem.hostseditor.core.dagger; import com.nilhcem.hostseditor.task.GenericTaskAsync; import com.nilhcem.hostseditor.task.ListHostsAsync; import com.nilhcem.hostseditor.ui.BaseActivity; import com.nilhcem.hostseditor.ui.addedit.AddEditHostFragment; import com.nilhcem.hostseditor.ui.list.ListHostsFragment; import javax.inject.Singleton; import dagger.Component; @Singleton @Component( modules = { HostsEditorModule.class } ) public interface HostsEditorComponent { void inject(BaseActivity activity); void inject(GenericTaskAsync async); void inject(AddEditHostFragment fragment); void inject(ListHostsAsync async); void inject(ListHostsFragment fragment); } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/core/dagger/HostsEditorModule.java ================================================ package com.nilhcem.hostseditor.core.dagger; import com.squareup.otto.Bus; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; @Module public class HostsEditorModule { @Provides @Singleton Bus provideBus() { return new Bus(); } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/core/log/ReleaseTree.java ================================================ package com.nilhcem.hostseditor.core.log; import android.util.Log; import timber.log.Timber; public class ReleaseTree extends Timber.Tree { @Override protected void log(int priority, String tag, String message, Throwable t) { // Only log ERROR, and WTF. if (priority > Log.WARN) { Log.println(priority, tag, message); } } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/core/util/Compatibility.java ================================================ package com.nilhcem.hostseditor.core.util; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.graphics.Point; import android.os.Build; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; public class Compatibility { private Compatibility() { throw new UnsupportedOperationException(); } /** * Checks if current SDK is compatible with the desired API level. * * @param apiLevel the required API level. * @return {@code true} if current OS is compatible. */ private static boolean isCompatible(int apiLevel) { return android.os.Build.VERSION.SDK_INT >= apiLevel; } @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public static Point getScreenDimensions(Context context) { Point size = new Point(); WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); if (Compatibility.isCompatible(Build.VERSION_CODES.HONEYCOMB_MR2)) { display.getSize(size); } else { size.set(display.getWidth(), display.getHeight()); } return size; } /** * This method converts dp unit to equivalent device specific value in pixels. * * @param dp A value in dp (Device independent pixels) unit. Which we need to convert into pixels. * @param context Context to get resources and device specific display metrics. * @return A float value to represent Pixels equivalent to dp according to device. */ public static float convertDpToPixel(float dp, Context context) { Resources resources = context.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); return dp * (metrics.densityDpi / 160f); } public static int convertDpToIntPixel(float dp, Context context) { return Math.round(convertDpToPixel(dp, context)); } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/core/util/InetAddresses.java ================================================ /* * Copyright (C) 2008 The Guava Authors * * NOTICE: THIS FILE WAS MODIFIED (removed all not required for the project) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nilhcem.hostseditor.core.util; import java.net.InetAddress; import java.nio.ByteBuffer; /** * Static utility methods pertaining to {@link InetAddress} instances. */ public final class InetAddresses { private static final int IPV4_PART_COUNT = 4; private static final int IPV6_PART_COUNT = 8; private InetAddresses() { } /** * Returns {@code true} if the supplied string is a valid IP string literal, * {@code false} otherwise. * * @param ipString {@code String} to evaluated as an IP string literal * @return {@code true} if the argument is a valid IP string literal */ public static boolean isInetAddress(String ipString) { return ipStringToBytes(ipString) != null; } private static byte[] ipStringToBytes(String ipString) { // Make a first pass to categorize the characters in this string. boolean hasColon = false; boolean hasDot = false; for (int i = 0; i < ipString.length(); i++) { char c = ipString.charAt(i); if (c == '.') { hasDot = true; } else if (c == ':') { if (hasDot) { return null; // Colons must not appear after dots. } hasColon = true; } else if (Character.digit(c, 16) == -1) { return null; // Everything else must be a decimal or hex digit. } } // Now decide which address family to parse. if (hasColon) { if (hasDot) { ipString = convertDottedQuadToHex(ipString); if (ipString == null) { return null; } } return textToNumericFormatV6(ipString); } else if (hasDot) { return textToNumericFormatV4(ipString); } return null; } private static byte[] textToNumericFormatV4(String ipString) { String[] address = ipString.split("\\.", IPV4_PART_COUNT + 1); if (address.length != IPV4_PART_COUNT) { return null; } byte[] bytes = new byte[IPV4_PART_COUNT]; try { for (int i = 0; i < bytes.length; i++) { bytes[i] = parseOctet(address[i]); } } catch (NumberFormatException ex) { return null; } return bytes; } private static byte[] textToNumericFormatV6(String ipString) { // An address can have [2..8] colons, and N colons make N+1 parts. String[] parts = ipString.split(":", IPV6_PART_COUNT + 2); if (parts.length < 3 || parts.length > IPV6_PART_COUNT + 1) { return null; } // Disregarding the endpoints, find "::" with nothing in between. // This indicates that a run of zeroes has been skipped. int skipIndex = -1; for (int i = 1; i < parts.length - 1; i++) { if (parts[i].length() == 0) { if (skipIndex >= 0) { return null; // Can't have more than one :: } skipIndex = i; } } int partsHi; // Number of parts to copy from above/before the "::" int partsLo; // Number of parts to copy from below/after the "::" if (skipIndex >= 0) { // If we found a "::", then check if it also covers the endpoints. partsHi = skipIndex; partsLo = parts.length - skipIndex - 1; if (parts[0].length() == 0 && --partsHi != 0) { return null; // ^: requires ^:: } if (parts[parts.length - 1].length() == 0 && --partsLo != 0) { return null; // :$ requires ::$ } } else { // Otherwise, allocate the entire address to partsHi. The endpoints // could still be empty, but parseHextet() will check for that. partsHi = parts.length; partsLo = 0; } // If we found a ::, then we must have skipped at least one part. // Otherwise, we must have exactly the right number of parts. int partsSkipped = IPV6_PART_COUNT - (partsHi + partsLo); if (!(skipIndex >= 0 ? partsSkipped >= 1 : partsSkipped == 0)) { return null; } // Now parse the hextets into a byte array. ByteBuffer rawBytes = ByteBuffer.allocate(2 * IPV6_PART_COUNT); try { for (int i = 0; i < partsHi; i++) { rawBytes.putShort(parseHextet(parts[i])); } for (int i = 0; i < partsSkipped; i++) { rawBytes.putShort((short) 0); } for (int i = partsLo; i > 0; i--) { rawBytes.putShort(parseHextet(parts[parts.length - i])); } } catch (NumberFormatException ex) { return null; } return rawBytes.array(); } private static String convertDottedQuadToHex(String ipString) { int lastColon = ipString.lastIndexOf(':'); String initialPart = ipString.substring(0, lastColon + 1); String dottedQuad = ipString.substring(lastColon + 1); byte[] quad = textToNumericFormatV4(dottedQuad); if (quad == null) { return null; } String penultimate = Integer.toHexString(((quad[0] & 0xff) << 8) | (quad[1] & 0xff)); String ultimate = Integer.toHexString(((quad[2] & 0xff) << 8) | (quad[3] & 0xff)); return initialPart + penultimate + ":" + ultimate; } private static byte parseOctet(String ipPart) { // Note: we already verified that this string contains only hex digits. int octet = Integer.parseInt(ipPart); // Disallow leading zeroes, because no clear standard exists on // whether these should be interpreted as decimal or octal. if (octet > 255 || (ipPart.startsWith("0") && ipPart.length() > 1)) { throw new NumberFormatException(); } return (byte) octet; } private static short parseHextet(String ipPart) { // Note: we already verified that this string contains only hex digits. int hextet = Integer.parseInt(ipPart, 16); if (hextet > 0xffff) { throw new NumberFormatException(); } return (short) hextet; } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/core/util/ThreadPreconditions.java ================================================ package com.nilhcem.hostseditor.core.util; import android.os.Looper; import com.nilhcem.hostseditor.BuildConfig; public final class ThreadPreconditions { private ThreadPreconditions() { throw new UnsupportedOperationException(); } public static void checkOnMainThread() { if (BuildConfig.DEBUG) { if (Thread.currentThread() != Looper.getMainLooper().getThread()) { throw new IllegalStateException("This method should be called from the Main Thread"); } } } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/event/CreatedHostEvent.java ================================================ package com.nilhcem.hostseditor.event; import com.nilhcem.hostseditor.core.Host; public class CreatedHostEvent { /** * Host (add mode), or the modified version of the Host entry (edit mode). */ public final Host editedHost; /** * Original version of the Host entry (edit mode) or {@code null} (add mode). */ public final Host originalHost; public CreatedHostEvent(Host original, Host edited) { originalHost = original; editedHost = edited; } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/event/LoadingEvent.java ================================================ package com.nilhcem.hostseditor.event; import android.content.Context; public class LoadingEvent { private final boolean mIsLoading; private final int mMessageRes; private final String mMessage; public LoadingEvent() { this(false, ""); } public LoadingEvent(boolean isLoading, int messageRes) { mIsLoading = isLoading; mMessageRes = messageRes; mMessage = null; } public LoadingEvent(boolean isLoading, String message) { mIsLoading = isLoading; mMessage = message; mMessageRes = 0; } public boolean isLoading() { return mIsLoading; } public String getMessage(Context context) { if (mMessage == null) { return context.getString(mMessageRes); } return mMessage; } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/event/RefreshHostsEvent.java ================================================ package com.nilhcem.hostseditor.event; import com.nilhcem.hostseditor.core.Host; import java.util.List; /** * Sent to the bus when hosts need to be refreshed. */ public class RefreshHostsEvent { public final List hosts; public RefreshHostsEvent(List refreshedHosts) { hosts = refreshedHosts; } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/event/StartAddEditActivityEvent.java ================================================ package com.nilhcem.hostseditor.event; import com.nilhcem.hostseditor.core.Host; public class StartAddEditActivityEvent { /** * The Host entry to modify (edit mode), or {@code null} (add mode). */ public final Host host; public StartAddEditActivityEvent(Host addEditHost) { host = addEditHost; } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/event/TaskCompletedEvent.java ================================================ package com.nilhcem.hostseditor.event; public class TaskCompletedEvent { public final String tag; public final boolean isSuccessful; public TaskCompletedEvent(String pTag, boolean pIsSuccessful) { tag = pTag; isSuccessful = pIsSuccessful; } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/task/AddEditHostAsync.java ================================================ package com.nilhcem.hostseditor.task; import android.content.Context; import com.nilhcem.hostseditor.R; import com.nilhcem.hostseditor.core.Host; import java.util.List; import timber.log.Timber; /** * AsyncTask that inserts or edits an host entry and triggers a {@code TaskCompletedEvent} event. */ public class AddEditHostAsync extends GenericTaskAsync { public AddEditHostAsync(Context appContext, boolean flagMsg) { super(appContext, flagMsg); } @Override protected void process(Host... params) { Timber.d("Add/Edit host"); Host host = params[0]; Host original = params[1]; List hosts = mHostsManager.getHosts(false); if (original == null) { hosts.add(host); } else { hosts.get(hosts.indexOf(original)).merge(host); } } @Override protected int getLoadingMsgRes() { return mFlagLoadingMsg ? R.string.loading_add : R.string.loading_edit; } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/task/GenericTaskAsync.java ================================================ package com.nilhcem.hostseditor.task; import android.content.Context; import android.os.AsyncTask; import com.nilhcem.hostseditor.HostsEditorApplication; import com.nilhcem.hostseditor.core.Host; import com.nilhcem.hostseditor.core.HostsManager; import com.nilhcem.hostseditor.event.LoadingEvent; import com.nilhcem.hostseditor.event.TaskCompletedEvent; import com.squareup.otto.Bus; import javax.inject.Inject; import timber.log.Timber; public abstract class GenericTaskAsync extends AsyncTask { @Inject Bus mBus; @Inject HostsManager mHostsManager; private Context mAppContext; protected boolean mFlagLoadingMsg; // which loading message (between 2) to display: (singular/plural) - (add/edit). public GenericTaskAsync(Context appContext, boolean flagMsg) { mAppContext = appContext; mFlagLoadingMsg = flagMsg; HostsEditorApplication.get(appContext).component().inject(this); } @Override protected void onPreExecute() { super.onPreExecute(); mBus.post(new LoadingEvent(true, getLoadingMsgRes())); } @Override protected Void doInBackground(Host... params) { process(params); if (!mHostsManager.saveHosts(mAppContext)) { cancel(false); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); Timber.d("Task fully executed"); mBus.post(new TaskCompletedEvent(getClass().getSimpleName(), true)); } @Override protected void onCancelled() { super.onCancelled(); Timber.w("Task cancelled"); mBus.post(new TaskCompletedEvent(getClass().getSimpleName(), false)); } /** * This method should edit the main {@code List}. * * @param params selected Hosts from the main ListView. */ protected abstract void process(Host... params); protected abstract int getLoadingMsgRes(); } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/task/ListHostsAsync.java ================================================ package com.nilhcem.hostseditor.task; import android.content.Context; import android.os.AsyncTask; import com.nilhcem.hostseditor.HostsEditorApplication; import com.nilhcem.hostseditor.R; import com.nilhcem.hostseditor.core.Host; import com.nilhcem.hostseditor.core.HostsManager; import com.nilhcem.hostseditor.event.LoadingEvent; import com.nilhcem.hostseditor.event.RefreshHostsEvent; import com.squareup.otto.Bus; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; /** * AsyncTask that gets all valid hosts and triggers a {@code RefreshHostEvent} event. */ public class ListHostsAsync extends AsyncTask> { @Inject Bus mBus; @Inject HostsManager mHostsManager; public ListHostsAsync(Context context) { HostsEditorApplication.get(context).component().inject(this); } @Override protected void onPreExecute() { super.onPreExecute(); mBus.post(new LoadingEvent(true, R.string.loading_hosts)); } @Override protected List doInBackground(Boolean... params) { Boolean forceRefresh = params[0]; if (forceRefresh == null) { forceRefresh = false; } List allHosts = mHostsManager.getHosts(forceRefresh); // Filter to get only valid hosts List validHosts = new ArrayList<>(); for (Host host : allHosts) { if (host.isValid()) { validHosts.add(host); } } return validHosts; } @Override protected void onPostExecute(List result) { super.onPostExecute(result); mBus.post(new RefreshHostsEvent(result)); } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/task/RemoveHostsAsync.java ================================================ package com.nilhcem.hostseditor.task; import android.content.Context; import com.nilhcem.hostseditor.R; import com.nilhcem.hostseditor.core.Host; import java.util.List; import timber.log.Timber; /** * AsyncTask that removes one or many host entries and triggers a {@code TaskCompletedEvent} event. */ public class RemoveHostsAsync extends GenericTaskAsync { public RemoveHostsAsync(Context appContext, boolean flagMsg) { super(appContext, flagMsg); } @Override protected void process(Host... params) { Timber.d("Remove hosts"); List hosts = mHostsManager.getHosts(false); for (Host host : params) { hosts.remove(host); } } @Override protected int getLoadingMsgRes() { return mFlagLoadingMsg ? R.string.loading_remove_single : R.string.loading_remove_multiple; } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/task/ToggleHostsAsync.java ================================================ package com.nilhcem.hostseditor.task; import android.content.Context; import com.nilhcem.hostseditor.R; import com.nilhcem.hostseditor.core.Host; import timber.log.Timber; /** * AsyncTask that toggles one or many host entries and triggers a {@code TaskCompletedEvent} event. */ public class ToggleHostsAsync extends GenericTaskAsync { public ToggleHostsAsync(Context appContext, boolean flagMsg) { super(appContext, flagMsg); } @Override protected void process(Host... params) { Timber.d("Toggle hosts"); for (Host host : params) { host.toggleComment(); } } @Override protected int getLoadingMsgRes() { return mFlagLoadingMsg ? R.string.loading_toggle_single : R.string.loading_toggle_multiple; } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/ui/BaseActivity.java ================================================ package com.nilhcem.hostseditor.ui; import android.os.Bundle; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.nilhcem.hostseditor.HostsEditorApplication; import com.squareup.otto.Bus; import javax.inject.Inject; /** * All activities should extend this for dependency injection. */ public abstract class BaseActivity extends SherlockFragmentActivity { @Inject protected Bus mBus; protected HostsEditorApplication mApp; @Override protected void onCreate(Bundle state) { super.onCreate(state); mApp = HostsEditorApplication.get(this); mApp.component().inject(this); } @Override protected void onResume() { super.onResume(); mBus.register(this); } @Override protected void onPause() { mBus.unregister(this); super.onPause(); } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/ui/BaseFragment.java ================================================ package com.nilhcem.hostseditor.ui; import android.app.Activity; import android.os.Bundle; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.nilhcem.hostseditor.BuildConfig; import com.nilhcem.hostseditor.HostsEditorApplication; import com.squareup.otto.Bus; import javax.inject.Inject; /** * All fragments should extend this for dependency injection. */ public class BaseFragment extends SherlockFragment { @Inject protected Bus mBus; protected HostsEditorApplication mApp; protected SherlockFragmentActivity mActivity; @Override public void onAttach(Activity activity) { if (BuildConfig.DEBUG && !(activity instanceof SherlockFragmentActivity)) { throw new UnsupportedOperationException("Activity must be a SherlockFragmentActivity"); } super.onAttach(activity); mApp = HostsEditorApplication.get(activity); mActivity = (SherlockFragmentActivity) activity; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public void onResume() { super.onResume(); mBus.register(this); } @Override public void onPause() { mBus.unregister(this); super.onPause(); } @Override public void onDetach() { mApp = null; mActivity = null; super.onDetach(); } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/ui/about/AboutDialogFragment.java ================================================ package com.nilhcem.hostseditor.ui.about; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.actionbarsherlock.app.SherlockDialogFragment; import com.nilhcem.hostseditor.R; import butterknife.ButterKnife; import butterknife.OnClick; public class AboutDialogFragment extends SherlockDialogFragment { public static final String TAG = AboutDialogFragment.class.getSimpleName(); private static final String GITHUB_URL = "https://github.com/Nilhcem/hosts-editor-android"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.about_dialog, container, false); ButterKnife.bind(this, view); getDialog().setTitle(R.string.about_title); return view; } @Override public void onDestroyView() { ButterKnife.unbind(this); super.onDestroyView(); } @OnClick(R.id.aboutGitHub) void openGitHubUrl() { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(GITHUB_URL)); startActivity(browserIntent); } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/ui/addedit/AddEditHostActivity.java ================================================ package com.nilhcem.hostseditor.ui.addedit; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.nilhcem.hostseditor.R; import com.nilhcem.hostseditor.core.Host; import com.nilhcem.hostseditor.event.CreatedHostEvent; import com.nilhcem.hostseditor.ui.BaseActivity; import com.nilhcem.hostseditor.ui.list.ListHostsActivity; import com.squareup.otto.Subscribe; public class AddEditHostActivity extends BaseActivity { public static final String EXTRA_HOST_ORIGINAL = "hostOriginal"; // useful in Edit mode, this is the original Host entry before being edited. public static final String EXTRA_HOST_MODIFIED = "hostModified"; // the new Host entry, after having been edited. private AddEditHostFragment mFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Host hostToEdit = getHostFromIntent(); initActionBar(hostToEdit); // Add fragment FragmentManager fm = getSupportFragmentManager(); mFragment = (AddEditHostFragment) fm.findFragmentByTag(AddEditHostFragment.TAG); if (mFragment == null) { mFragment = AddEditHostFragment.newInstance(hostToEdit); FragmentTransaction ft = fm.beginTransaction(); ft.replace(android.R.id.content, mFragment, AddEditHostFragment.TAG); ft.commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.add_edit_menu, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem item = menu.findItem(R.id.action_add_rm_comment); if (mFragment.hasComment()) { item.setTitle(R.string.action_remove_comment); } else { item.setTitle(R.string.action_add_comment); } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent intent = new Intent(this, ListHostsActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); return true; case R.id.action_add_rm_comment: mFragment.toggleCommentVisibility(); return true; default: return super.onOptionsItemSelected(item); } } @Subscribe public void onHostCreatedFromFragment(CreatedHostEvent event) { Intent returnIntent = new Intent(); returnIntent.putExtra(EXTRA_HOST_ORIGINAL, event.originalHost); returnIntent.putExtra(EXTRA_HOST_MODIFIED, event.editedHost); setResult(RESULT_OK, returnIntent); finish(); } private Host getHostFromIntent() { Host host = null; Bundle bundle = getIntent().getExtras(); if (bundle != null) { host = bundle.getParcelable(EXTRA_HOST_ORIGINAL); } return host; } private void initActionBar(Host hostToEdit) { int titleRes; if (hostToEdit == null) { titleRes = R.string.add_host_title; } else { titleRes = R.string.edit_host_title; } ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(titleRes); } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/ui/addedit/AddEditHostFragment.java ================================================ package com.nilhcem.hostseditor.ui.addedit; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.nilhcem.hostseditor.R; import com.nilhcem.hostseditor.core.Host; import com.nilhcem.hostseditor.core.util.InetAddresses; import com.nilhcem.hostseditor.event.CreatedHostEvent; import com.nilhcem.hostseditor.ui.BaseFragment; import java.util.regex.Pattern; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public class AddEditHostFragment extends BaseFragment { public static final String TAG = AddEditHostFragment.class.getSimpleName(); private static final String ARG_HOST = "mInitialHost"; private static final Pattern HOSTNAME_INVALID_CHARS_PATTERN = Pattern.compile("^.*[#'\",\\\\]+.*$"); private Host mInitialHost; // "edit mode" only - null for "add mode" private AlertDialog mErrorAlert; @Bind(R.id.addEditHostIp) EditText mIp; @Bind(R.id.addEditHostName) EditText mHostName; @Bind(R.id.addEditComment) EditText mComment; @Bind(R.id.addEditCommentLabel) TextView mCommentLabel; @Bind(R.id.addEditHostButton) Button mButton; public static AddEditHostFragment newInstance(Host hostToEdit) { AddEditHostFragment fragment = new AddEditHostFragment(); if (hostToEdit != null) { Bundle args = new Bundle(); args.putParcelable(ARG_HOST, hostToEdit); fragment.setArguments(args); } return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mApp.component().inject(this); Bundle arguments = getArguments(); if (arguments != null) { mInitialHost = arguments.getParcelable(ARG_HOST); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.add_edit_host_layout, container, false); ButterKnife.bind(this, view); if (mInitialHost == null) { mButton.setText(R.string.add_host_title); } else { mIp.setText(mInitialHost.getIp()); mHostName.setText(mInitialHost.getHostName()); mButton.setText(R.string.edit_host_title); String comment = mInitialHost.getComment(); if (!TextUtils.isEmpty(comment)) { mComment.setText(comment); toggleCommentVisibility(); } } return view; } @Override public void onStop() { if (mErrorAlert != null) { mErrorAlert.dismiss(); } super.onStop(); } @Override public void onDestroyView() { ButterKnife.unbind(this); super.onDestroyView(); } @OnClick(R.id.addEditHostButton) void onAddEditHostButtonClicked(Button button) { if (button.getId() == R.id.addEditHostButton) { String ip = mIp.getText().toString(); String hostname = mHostName.getText().toString(); String comment = mComment.getText().toString(); if (TextUtils.isEmpty(comment)) { comment = null; } int error = checkFormErrors(ip, hostname); if (error == 0) { Host edited = new Host(ip, hostname, comment, false, true); mBus.post(new CreatedHostEvent(mInitialHost, edited)); } else { mErrorAlert = new AlertDialog.Builder(mActivity) .setTitle(R.string.add_edit_error_title) .setMessage(error) .setCancelable(true) .setNeutralButton(R.string.add_edit_error_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Do nothing } }) .create(); mErrorAlert.show(); } } } public boolean hasComment() { return mComment.getVisibility() == View.VISIBLE; } public void toggleCommentVisibility() { int visibility; if (hasComment()) { visibility = View.GONE; mComment.setText(""); } else { visibility = View.VISIBLE; } mComment.setVisibility(visibility); mCommentLabel.setVisibility(visibility); } private int checkFormErrors(String ip, String hostname) { int error = 0; if (TextUtils.isEmpty(hostname) || HOSTNAME_INVALID_CHARS_PATTERN.matcher(hostname).matches()) { error = R.string.add_edit_error_hostname; } if (TextUtils.isEmpty(ip) || !InetAddresses.isInetAddress(ip)) { error = R.string.add_edit_error_ip; } return error; } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsActivity.java ================================================ package com.nilhcem.hostseditor.ui.list; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.widget.SearchView; import com.nilhcem.hostseditor.R; import com.nilhcem.hostseditor.core.Host; import com.nilhcem.hostseditor.event.LoadingEvent; import com.nilhcem.hostseditor.event.StartAddEditActivityEvent; import com.nilhcem.hostseditor.ui.BaseActivity; import com.nilhcem.hostseditor.ui.about.AboutDialogFragment; import com.nilhcem.hostseditor.ui.addedit.AddEditHostActivity; import com.squareup.otto.Subscribe; import butterknife.Bind; import butterknife.ButterKnife; import timber.log.Timber; public class ListHostsActivity extends BaseActivity { private static final int REQUESTCODE_ADDEDIT_ACTIVITY = 1; private static final String STR_EMPTY = ""; private static final String INSTANCE_STATE_LOADING = "loading"; private static final String INSTANCE_STATE_LOADING_MESSAGE = "loadingMessage"; private static final String INSTANCE_STATE_SEARCH = "search"; @Bind(R.id.listLoading) ProgressBar mProgressBar; @Bind(R.id.listLoadingMsg) TextView mLoadingMsg; private ListHostsFragment mFragment; private String mSearchQuery = STR_EMPTY; private MenuItem mSearchItem; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_hosts_layout); ButterKnife.bind(this); FragmentManager fm = getSupportFragmentManager(); mFragment = (ListHostsFragment) fm.findFragmentById(R.id.listHostsFragment); if (savedInstanceState == null) { onLoadingEvent(new LoadingEvent(true, R.string.loading_hosts)); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.list_menu, menu); // Init search mSearchItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) mSearchItem.getActionView(); if (searchView != null) { searchView.setQueryHint(getString(R.string.action_search)); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { mSearchItem.collapseActionView(); return true; } @Override public boolean onQueryTextChange(String newText) { Timber.d("Search query: %s", newText); setSearchQuery(newText); mFragment.filterList(newText); return true; } }); } return true; } @Override protected void onResume() { super.onResume(); mFragment.filterList(mSearchQuery); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (!TextUtils.isEmpty(mSearchQuery)) { // Revert search setSearchQuery(STR_EMPTY); mFragment.filterList(mSearchQuery); return true; } break; case KeyEvent.KEYCODE_SEARCH: mSearchItem.expandActionView(); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_add_host: mBus.post(new StartAddEditActivityEvent(null)); return true; case R.id.action_reload_hosts: mFragment.refreshHosts(true); return true; case R.id.action_select_all: mFragment.selectAll(); return true; case R.id.action_about: displayAboutDialog(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Timber.d("Activity result received"); if (requestCode == REQUESTCODE_ADDEDIT_ACTIVITY) { if (resultCode == RESULT_OK) { Host modified = data.getParcelableExtra(AddEditHostActivity.EXTRA_HOST_MODIFIED); Host original = data.getParcelableExtra(AddEditHostActivity.EXTRA_HOST_ORIGINAL); boolean addMode = (original == null); onLoadingEvent(new LoadingEvent(true, addMode ? R.string.loading_add : R.string.loading_edit)); mFragment.addEditHost(addMode, new Host[]{modified, original}); } } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(INSTANCE_STATE_LOADING, mProgressBar.getVisibility() == View.VISIBLE); outState.putString(INSTANCE_STATE_LOADING_MESSAGE, mLoadingMsg.getText().toString()); outState.putString(INSTANCE_STATE_SEARCH, mSearchQuery); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); boolean isLoading = savedInstanceState.getBoolean(INSTANCE_STATE_LOADING, true); if (isLoading) { String loadingMsg = savedInstanceState.getString(INSTANCE_STATE_LOADING_MESSAGE); if (loadingMsg == null) { loadingMsg = STR_EMPTY; } onLoadingEvent(new LoadingEvent(true, loadingMsg)); } setSearchQuery(savedInstanceState.getString(INSTANCE_STATE_SEARCH)); } @Override protected void onDestroy() { ButterKnife.unbind(this); super.onDestroy(); } @Subscribe public void onStartAddEditActivityEvent(StartAddEditActivityEvent event) { Timber.d("Ready to start AddEditActivity"); Intent intent = new Intent(this, AddEditHostActivity.class); intent.putExtra(AddEditHostActivity.EXTRA_HOST_ORIGINAL, event.host); startActivityForResult(intent, REQUESTCODE_ADDEDIT_ACTIVITY); } @Subscribe public void onLoadingEvent(LoadingEvent event) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); mLoadingMsg.setText(event.getMessage(this)); if (event.isLoading()) { Timber.d("Start loading"); if (mSearchItem != null) { setSearchQuery(STR_EMPTY); mSearchItem.collapseActionView(); } mProgressBar.setVisibility(View.VISIBLE); mLoadingMsg.setVisibility(View.VISIBLE); ft.hide(mFragment); } else { Timber.d("Stop loading"); mProgressBar.setVisibility(View.GONE); mLoadingMsg.setVisibility(View.GONE); ft.show(mFragment); } ft.commitAllowingStateLoss(); } private void setSearchQuery(String searchQuery) { mSearchQuery = searchQuery; setActionBarTitle(); } private void setActionBarTitle() { int titleRes; if (TextUtils.isEmpty(mSearchQuery)) { titleRes = R.string.app_name; } else { titleRes = R.string.action_search_results; } getSupportActionBar().setTitle(titleRes); } private void displayAboutDialog() { FragmentManager fm = getSupportFragmentManager(); AboutDialogFragment dialog = new AboutDialogFragment(); dialog.show(fm, AboutDialogFragment.TAG); } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsAdapter.java ================================================ package com.nilhcem.hostseditor.ui.list; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView.LayoutParams; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; import com.nilhcem.hostseditor.core.Host; import com.nilhcem.hostseditor.core.util.Compatibility; import com.nilhcem.hostseditor.core.util.ThreadPreconditions; import com.nilhcem.hostseditor.ui.widget.CheckableHostItem; import java.util.Collections; import java.util.List; import javax.inject.Inject; import timber.log.Timber; public class ListHostsAdapter extends BaseAdapter implements Filterable { private final ListHostsSearchFilter mSearchFilter; private List mHosts = Collections.emptyList(); private Context mAppContext; private int mIpMinWidth; private int mIpMaxWidth; @Inject public ListHostsAdapter(ListHostsSearchFilter searchFilter) { mSearchFilter = searchFilter; } public void init(Context appContext) { mAppContext = appContext; } public void updateHosts(List hosts) { ThreadPreconditions.checkOnMainThread(); if (hosts == null) { mHosts = Collections.emptyList(); } else { mHosts = hosts; } notifyDataSetChanged(); } public void computeViewWidths(Context context) { // The IP column can be very large, especially when it holds ipv6 with 39 chars. // Its size has to be generated programmatically, as it should fit with the device's width. // A tablet can afford having a large column but not a phone. int screenWidth = Compatibility.getScreenDimensions(context).x; Timber.d("Screen width: %d", screenWidth); // 1: Compute minimum width. // Min width must be between [100dp, 160dp]. If possible, 30% of screen width. int minWidth = screenWidth * 30 / 100; int minRange = Compatibility.convertDpToIntPixel(100f, context); int maxRange = Compatibility.convertDpToIntPixel(160f, context); if (minWidth < minRange) { minWidth = minRange; } if (minWidth > maxRange) { minWidth = maxRange; } // 2: Compute maximum width, usually 35% of screen width. int maxWidth = screenWidth * 35 / 100; if (maxWidth < minWidth) { maxWidth = minWidth; } Timber.d("Min width: %d - Max width: %d", minWidth, maxWidth); mIpMinWidth = minWidth; mIpMaxWidth = maxWidth; } @Override public int getCount() { return mHosts.size(); } @Override public Host getItem(int position) { return mHosts.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { CheckableHostItem view; if (convertView == null) { view = new CheckableHostItem(mAppContext); } else { view = (CheckableHostItem) convertView; } Host host = getItem(position); view.init(host, mIpMinWidth, mIpMaxWidth); return view; } @Override public Filter getFilter() { return mSearchFilter; } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsFragment.java ================================================ package com.nilhcem.hostseditor.ui.list; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ListView; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.nilhcem.hostseditor.R; import com.nilhcem.hostseditor.core.Host; import com.nilhcem.hostseditor.event.LoadingEvent; import com.nilhcem.hostseditor.event.RefreshHostsEvent; import com.nilhcem.hostseditor.event.StartAddEditActivityEvent; import com.nilhcem.hostseditor.event.TaskCompletedEvent; import com.nilhcem.hostseditor.task.AddEditHostAsync; import com.nilhcem.hostseditor.task.ListHostsAsync; import com.nilhcem.hostseditor.task.RemoveHostsAsync; import com.nilhcem.hostseditor.task.ToggleHostsAsync; import com.nilhcem.hostseditor.ui.BaseFragment; import com.squareup.otto.Subscribe; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.inject.Inject; import butterknife.Bind; import butterknife.ButterKnife; import timber.log.Timber; public class ListHostsFragment extends BaseFragment implements OnItemClickListener, OnItemLongClickListener { @Inject ListHostsAdapter mAdapter; @Bind(R.id.listHosts) ListView mListView; private ActionMode mMode; private MenuItem mEditMenuItem; private Dialog mDisplayedDialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mApp.component().inject(this); mAdapter.init(mApp); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { boolean firstCall = (mListView == null); View view = inflater.inflate(R.layout.list_hosts_fragment, container, false); ButterKnife.bind(this, view); mListView.setAdapter(mAdapter); mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); mListView.setFastScrollEnabled(true); mListView.setItemsCanFocus(false); mListView.setOnItemClickListener(this); mListView.setOnItemLongClickListener(this); View emptyLayout = view.findViewById(R.id.listEmptyLayout); if (emptyLayout != null) { mListView.setEmptyView(emptyLayout); } mAdapter.computeViewWidths(mActivity); if (firstCall) { refreshHosts(false); } return view; } @Override public void onPause() { finishActionMode(); if (mDisplayedDialog != null) { mDisplayedDialog.dismiss(); mDisplayedDialog = null; } super.onPause(); } @Override public void onDestroyView() { ButterKnife.unbind(this); super.onDestroyView(); } @Override public void onItemClick(AdapterView parent, View view, int position, long id) { int nbCheckedElements = 0; SparseBooleanArray checked = mListView.getCheckedItemPositions(); for (int i = 0; i < checked.size(); i++) { if (checked.valueAt(i)) { nbCheckedElements++; } } displayActionMode(nbCheckedElements); } @Override public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { if (mMode == null) { Host host = mAdapter.getItem(position); mBus.post(new StartAddEditActivityEvent(host)); return true; } return false; } @Subscribe public void onTaskFinished(TaskCompletedEvent task) { Timber.d("Task %s finished", task.tag); if (task.isSuccessful) { refreshHosts(false); } else { displayErrorDialog(); } } @Subscribe public void onHostsRefreshed(RefreshHostsEvent hosts) { Timber.d("Refreshing listview"); finishActionMode(); mAdapter.updateHosts(hosts.hosts); mBus.post(new LoadingEvent()); } public void addEditHost(boolean addMode, Host[] hosts) { new AddEditHostAsync(mApp, addMode).execute(hosts); } public void refreshHosts(boolean forceRefresh) { new ListHostsAsync(mApp).execute(forceRefresh); } public void selectAll() { int nbElem = mAdapter.getCount(); if (nbElem > 0) { for (int i = 0; i < nbElem; i++) { mListView.setItemChecked(i, true); } displayActionMode(nbElem); } } public void filterList(String filter) { mAdapter.getFilter().filter(filter); } private void displayActionMode(int nbCheckedElements) { if (nbCheckedElements > 0) { if (mMode == null) { mMode = mActivity.startActionMode(new ModeCallback()); } if (mEditMenuItem != null) { mEditMenuItem.setVisible(nbCheckedElements == 1); } mMode.setTitle(String.format(Locale.US, getString(R.string.list_menu_selected), nbCheckedElements)); } else { finishActionMode(); } } private final class ModeCallback implements ActionMode.Callback { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mActivity.getSupportMenuInflater(); inflater.inflate(R.menu.list_contextual_actions, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { mEditMenuItem = menu.findItem(R.id.cab_action_edit); return false; } @Override public void onDestroyActionMode(ActionMode mode) { for (int i = 0; i < mListView.getAdapter().getCount(); i++) { mListView.setItemChecked(i, false); } mMode = null; mEditMenuItem = null; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { Host[] selectedItems = getSelectedItems(); switch (item.getItemId()) { case R.id.cab_action_edit: mBus.post(new StartAddEditActivityEvent(selectedItems[0])); break; case R.id.cab_action_delete: displayDeleteConfirmationDialog(selectedItems); break; case R.id.cab_action_toggle: new ToggleHostsAsync(mApp, selectedItems.length == 1).execute(selectedItems); break; default: return false; } mode.finish(); return true; } private Host[] getSelectedItems() { List items = new ArrayList<>(); int len = mListView.getCount(); SparseBooleanArray checked = mListView.getCheckedItemPositions(); for (int i = 0; i < len; i++) { if (checked.get(i)) { items.add(mAdapter.getItem(i)); } } return items.toArray(new Host[items.size()]); } } private void displayDeleteConfirmationDialog(final Host[] selectedItems) { mDisplayedDialog = new AlertDialog.Builder(mActivity) .setTitle(R.string.delete_dialog_title) .setMessage(getResources().getQuantityText(R.plurals.delete_dialog_content, selectedItems.length)) .setPositiveButton(R.string.delete_dialog_delete, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new RemoveHostsAsync(mApp, selectedItems.length == 1).execute(selectedItems); } }) .setNegativeButton(R.string.delete_dialog_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Do nothing } }) .create(); mDisplayedDialog.show(); } private void displayErrorDialog() { mBus.post(new LoadingEvent()); mDisplayedDialog = new AlertDialog.Builder(mActivity) .setTitle(R.string.list_error_title) .setMessage(R.string.list_error_content) .setNeutralButton(R.string.list_error_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { refreshHosts(true); } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { refreshHosts(true); } }) .create(); mDisplayedDialog.show(); } private void finishActionMode() { if (mMode != null) { mMode.finish(); } } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsSearchFilter.java ================================================ package com.nilhcem.hostseditor.ui.list; import android.text.TextUtils; import android.widget.Filter; import com.nilhcem.hostseditor.core.Host; import com.nilhcem.hostseditor.core.HostsManager; import com.nilhcem.hostseditor.event.RefreshHostsEvent; import com.squareup.otto.Bus; import java.util.List; import javax.inject.Inject; import timber.log.Timber; public class ListHostsSearchFilter extends Filter { private final Bus mBus; private final HostsManager mHostsManager; @Inject public ListHostsSearchFilter(Bus bus, HostsManager hostsManager) { mBus = bus; mHostsManager = hostsManager; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, FilterResults results) { if (!TextUtils.isEmpty(constraint)) { Timber.d("Publishing result for: %s", constraint); } mBus.post(new RefreshHostsEvent((List) results.values)); } @Override protected FilterResults performFiltering(CharSequence constraint) { if (!TextUtils.isEmpty(constraint)) { Timber.d("Perform filtering for: %s", constraint); } FilterResults results = new FilterResults(); results.values = mHostsManager.filterHosts(constraint); return results; } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/ui/widget/CheckableHostItem.java ================================================ package com.nilhcem.hostseditor.ui.widget; import android.content.Context; import android.content.res.Resources; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.widget.Checkable; import android.widget.RelativeLayout; import android.widget.TextView; import com.nilhcem.hostseditor.R; import com.nilhcem.hostseditor.core.Host; import java.util.Locale; import butterknife.Bind; import butterknife.ButterKnife; /** * Custom component that implements the Checkable interface. * * @see "http://www.marvinlabs.com/2010/10/29/custom-listview-ability-check-items/" */ public class CheckableHostItem extends RelativeLayout implements Checkable { @Bind(R.id.hostItemIp) TextView mIp; @Bind(R.id.hostItemHostname) TextView mHostname; @Bind(R.id.hostItemComment) TextView mComment; @Bind(R.id.hostItemCheckbox) InertCheckBox mCheckbox; private int mTextColor; private int mCommentColor; public CheckableHostItem(Context context) { super(context); initLayout(context); } private void initLayout(Context context) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.checkable_host_item, this, true); ButterKnife.bind(this, view); Resources res = context.getResources(); mTextColor = res.getColor(R.color.list_hosts_entry); mCommentColor = res.getColor(R.color.list_hosts_comment); } public void init(Host host, int ipMinWidth, int ipMaxWidth) { String ip = String.format(Locale.US, "%s%s", (host.isCommented() ? Host.STR_COMMENT : ""), host.getIp()); int textColor; if (host.isCommented()) { textColor = mCommentColor; } else { textColor = mTextColor; } mIp.setText(ip); mIp.setTextColor(textColor); mIp.setMinimumWidth(ipMinWidth); mIp.setMaxWidth(ipMaxWidth); mHostname.setText(host.getHostName()); mHostname.setTextColor(textColor); mCheckbox.setChecked(false); String comment = host.getComment(); if (TextUtils.isEmpty(comment)) { mComment.setVisibility(View.GONE); } else { mComment.setText(String.format(Locale.US, "%s%s", Host.STR_COMMENT, comment)); mComment.setVisibility(View.VISIBLE); } } @Override public boolean isChecked() { return mCheckbox.isChecked(); } @Override public void setChecked(boolean checked) { mCheckbox.setChecked(checked); } @Override public void toggle() { mCheckbox.toggle(); } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/ui/widget/InertCheckBox.java ================================================ package com.nilhcem.hostseditor.ui.widget; import android.content.Context; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.MotionEvent; import android.widget.CheckBox; /** * CheckBox that does not react to any user event in order to let the container handle them. */ public class InertCheckBox extends CheckBox { public InertCheckBox(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public InertCheckBox(Context context, AttributeSet attrs) { super(context, attrs); } public InertCheckBox(Context context) { super(context); } @Override public boolean onTouchEvent(MotionEvent event) { return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return false; } @Override public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return false; } @Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { return false; } @Override public boolean onKeyShortcut(int keyCode, KeyEvent event) { return false; } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { return false; } @Override public boolean onTrackballEvent(MotionEvent event) { return false; } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/ui/widget/TypefacedButton.java ================================================ package com.nilhcem.hostseditor.ui.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.Button; /** * Button using a custom font. * * @see TypefacedTextView */ public final class TypefacedButton extends Button { public TypefacedButton(Context context, AttributeSet attrs) { super(context, attrs); TypefacedTextView.applyFont(context, attrs, this); } } ================================================ FILE: app/src/main/java/com/nilhcem/hostseditor/ui/widget/TypefacedTextView.java ================================================ package com.nilhcem.hostseditor.ui.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.TextView; import com.nilhcem.hostseditor.R; /** * TextView using a custom font. * * @see "http://stackoverflow.com/questions/4395309/android-want-to-set-custom-fonts-for-whole-application-not-runtime/9199258#9199258" */ public final class TypefacedTextView extends TextView { public TypefacedTextView(Context context, AttributeSet attrs) { super(context, attrs); // Typeface.createFromAsset doesn't work in the layout editor. Skipping... if (isInEditMode()) { return; } TypefacedTextView.applyFont(context, attrs, this); } static void applyFont(Context context, AttributeSet attrs, TextView view) { TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.TypefacedTextView); if (styledAttrs != null) { String fontName = styledAttrs.getString(R.styleable.TypefacedTextView_typeface); styledAttrs.recycle(); if (fontName != null) { Typeface typeface = Typeface.createFromAsset(context.getAssets(), fontName); view.setTypeface(typeface); } } } } ================================================ FILE: app/src/main/res/layout/about_dialog.xml ================================================ ================================================ FILE: app/src/main/res/layout/add_edit_host_layout.xml ================================================ ================================================ FILE: app/src/main/res/layout/checkable_host_item.xml ================================================ ================================================ FILE: app/src/main/res/layout/list_hosts_empty.xml ================================================ ================================================ FILE: app/src/main/res/layout/list_hosts_fragment.xml ================================================ ================================================ FILE: app/src/main/res/layout/list_hosts_layout.xml ================================================ ================================================ FILE: app/src/main/res/menu/add_edit_menu.xml ================================================ ================================================ FILE: app/src/main/res/menu/list_contextual_actions.xml ================================================ ================================================ FILE: app/src/main/res/menu/list_menu.xml ================================================ ================================================ FILE: app/src/main/res/values/attrs.xml ================================================ ================================================ FILE: app/src/main/res/values/colors.xml ================================================ #fff3f3f3 #ff909090 ================================================ FILE: app/src/main/res/values/dimens.xml ================================================ 16dp 16dp 20dp 16sp ================================================ FILE: app/src/main/res/values/strings.xml ================================================ Hosts Editor Search Search results Add Host Reload host entries Select all hosts About Add Hostname Edit Hostname IP Address: Hostname: Comment: Error IP address is invalid Hostname is invalid OK Add comment Remove comment No \'hosts\' records found. We couldn\'t find any host entry.\nFeel free to add some! %d selected Edit Delete Toggle Error Can\'t edit hosts file, make sure you have root/SuperUser rights.\nThe app should be allowed to request super user access. OK Delete Delete selected host? Delete selected hosts? Cancel Delete Loading host entries Adding entry Editing entry Removing entry Removing entries Toggling entry Toggling entries About Hosts Editor This app lets you modify your /etc/hosts file on Android.\nYou might need to reboot to clear your DNS cache after any change. 2013 – 2015\nhttp://www.nilhcem.com GitHub ================================================ FILE: app/src/main/res/values/styles.xml ================================================ ================================================ FILE: app/src/main/res/values-sw720dp-land/dimens.xml ================================================ 128dp ================================================ FILE: build.gradle ================================================ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.2.3' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4' } } allprojects { repositories { jcenter() } } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Mon Jul 13 13:14:00 GMT 2015 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip ================================================ FILE: gradlew ================================================ #!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # For Cygwin, ensure paths are in UNIX format before anything is touched. if $cygwin ; then [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` fi # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >&- APP_HOME="`pwd -P`" cd "$SAVED" >&- CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" ================================================ FILE: gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: settings.gradle ================================================ include ':app'