xref: /OpenGrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/TandemPath.java (revision 5d9f3aa0ca3da3a714233f987fa732f62c0965f6)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * See LICENSE.txt included in this distribution for the specific
9  * language governing permissions and limitations under the License.
10  *
11  * When distributing Covered Code, include this CDDL HEADER in each
12  * file and include the License file at LICENSE.txt.
13  * If applicable, add the following below this CDDL HEADER, with the
14  * fields enclosed by brackets "[]" replaced with your own identifying
15  * information: Portions Copyright [yyyy] [name of copyright owner]
16  *
17  * CDDL HEADER END
18  */
19 
20 /*
21  * Copyright (c) 2018, Chris Fraire <cfraire@me.com>.
22  */
23 package org.opengrok.indexer.util;
24 
25 import java.io.File;
26 
27 /**
28  * Represents a utility class for creating a path to operate in tandem with
29  * an original path by adding a new file extension but limiting the length
30  * of the filename component of the new path to 255 UTF-8 encoded bytes if
31  * necessary by truncating and packing in a Base64-encoded SHA-256 hash of the
32  * original file name component.
33  */
34 public class TandemPath {
35 
36     /** Private to enforce static. */
TandemPath()37     private TandemPath() {
38     }
39 
40     /**
41      * Appends an ASCII extension to the specified {@code filePath}, truncating
42      * and packing in a SHA-256 hash if the UTF-8 encoding of the filename
43      * component of the path would exceed 254 bytes and arriving at a final
44      * size of 255 bytes in that special case.
45      * @param filePath a defined instance
46      * @param asciiExtension a defined instance that is expected to be only
47      *                       ASCII so that its UTF-8 form is the same length
48      * @return a transformed path whose filename component's UTF-8 encoding is
49      * not more than 255 bytes.
50      * @throws IllegalArgumentException {@code asciiExtension} is too long to
51      * allow packing a SHA-256 hash in the transformation.
52      */
join(String filePath, String asciiExtension)53     public static String join(String filePath, String asciiExtension) {
54 
55         File file = new File(filePath);
56         String newName = TandemFilename.join(file.getName(), asciiExtension);
57         File newFile = new File(file.getParent(), newName);
58         return newFile.getPath();
59     }
60 }
61