1/*
2 * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24
25public class TransformUtil {
26    public static final String BeforePattern = "this-should-be-transformed";
27    public static final String AfterPattern  = "this-has-been--transformed";
28    public static final String ParentCheckPattern = "parent-transform-check: ";
29    public static final String ChildCheckPattern = "child-transform-check: ";
30
31    /**
32     * @return the number of occurrences of the <code>from</code> string that
33     * have been replaced.
34     */
35    public static int replace(byte buff[], String from, String to) {
36        if (to.length() != from.length()) {
37            throw new RuntimeException("bad strings");
38        }
39        byte f[] = asciibytes(from);
40        byte t[] = asciibytes(to);
41        byte f0 = f[0];
42
43        int numReplaced = 0;
44        int max = buff.length - f.length;
45        for (int i = 0; i < max; ) {
46            if (buff[i] == f0 && replace(buff, f, t, i)) {
47                i += f.length;
48                numReplaced++;
49            } else {
50                i++;
51            }
52        }
53        return numReplaced;
54    }
55
56    public static boolean replace(byte buff[], byte f[], byte t[], int i) {
57        for (int x = 0; x < f.length; x++) {
58            if (buff[x+i] != f[x]) {
59                return false;
60            }
61        }
62        for (int x = 0; x < f.length; x++) {
63            buff[x+i] = t[x];
64        }
65        return true;
66    }
67
68    static byte[] asciibytes(String s) {
69        byte b[] = new byte[s.length()];
70        for (int i = 0; i < b.length; i++) {
71            b[i] = (byte)s.charAt(i);
72        }
73        return b;
74    }
75}
76