1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.vafer.jdeb.utils;
17
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.OutputStream;
21 import java.text.ParseException;
22
23
24
25
26
27
28
29
30
31 public final class Utils {
32
33 public static int copy( final InputStream pInput, final OutputStream pOutput ) throws IOException {
34 final byte[] buffer = new byte[2048];
35 int count = 0;
36 int n = 0;
37 while (-1 != (n = pInput.read(buffer))) {
38 pOutput.write(buffer, 0, n);
39 count += n;
40 }
41 return count;
42 }
43
44 public static String toHex( final byte[] pBytes ) {
45 final StringBuffer sb = new StringBuffer();
46
47 for (int i = 0; i < pBytes.length; ++i) {
48 sb.append(Integer.toHexString((pBytes[i]>>4) & 0x0f));
49 sb.append(Integer.toHexString(pBytes[i] & 0x0f));
50 }
51
52 return sb.toString();
53 }
54
55 public static String stripPath( final int p, final String s ) {
56
57 if (p <= 0) {
58 return s;
59 }
60
61 int x = 0;
62 for (int i=0 ; i<p; i++) {
63 x = s.indexOf('/', x);
64 if (x < 0) {
65 return s;
66 }
67 }
68
69 return s.substring(x+1);
70 }
71
72 public static String stripLeadingSlash( final String s ) {
73 if (s == null) {
74 return s;
75 }
76 if (s.length() == 0) {
77 return s;
78 }
79 if (s.charAt(0) == '/') {
80 return s.substring(1);
81 }
82 return s;
83 }
84
85
86
87
88
89
90
91
92
93
94 public static String replaceVariables(final VariableResolver pResolver, final String pExpression, final String pOpen, final String pClose) throws ParseException {
95
96 final char[] s = pExpression.toCharArray();
97
98 final char[] open = pOpen.toCharArray();
99 final char[] close = pClose.toCharArray();
100
101 final StringBuffer out = new StringBuffer();
102 StringBuffer sb = new StringBuffer();
103 char[] watch = open;
104 int w = 0;
105 for (int i = 0; i < s.length; i++) {
106 char c = s[i];
107
108 if (c == watch[w]) {
109 w++;
110 if (watch.length == w) {
111
112
113 if (watch == open) {
114
115 out.append(sb);
116 sb = new StringBuffer();
117
118 watch = close;
119 } else if (watch == close) {
120
121 final String variable = (String) pResolver.get(sb.toString());
122 if (variable != null) {
123 out.append(variable);
124 } else {
125 throw new ParseException("Unknown variable " + sb, i);
126 }
127 sb = new StringBuffer();
128
129 watch = open;
130 }
131 w = 0;
132 }
133 } else {
134
135 if (w > 0) {
136 sb.append(watch, 0, w);
137 }
138
139 sb.append(c);
140
141 w = 0;
142 }
143 }
144
145 if (watch == close) {
146 out.append(open);
147 }
148 out.append(sb);
149
150 return out.toString();
151 }
152
153 }